package zk;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class Client {
    private ComboPooledDataSource ds = new ComboPooledDataSource();
//    private String jdbcUrl = "jdbc:mysql://master:3366/zk?useUnicode=true&characterEncoding=utf8&useSSL=false";
//    private String user;
//    private String passwd = "12345678";
    private String jdbcUrl, user, passwd;

    public Client() throws PropertyVetoException {
        ZkClient zkClient = new ZkClient("master:2181");
        zkClient.setZkSerializer(new ZkStrSerializer());
        boolean exists = zkClient.exists("/zk_homework");
        if(!exists){
            System.out.println("node does not exists");
            System.exit(1);
        }
        System.out.println("connect to zk");
        Object o = zkClient.readData("/zk_homework/url");
        Object o1 = zkClient.readData("/zk_homework/user");
        Object o2 = zkClient.readData("/zk_homework/passwd");
        jdbcUrl = String.valueOf(o);
        user = String.valueOf(o1);
        System.out.println(user);
        passwd = String.valueOf(o2);
        ds.setDriverClass("com.mysql.jdbc.Driver");
        setConnection();

        zkClient.subscribeDataChanges("/zk_homework/user", new IZkDataListener() {
            public void handleDataChange(String path, Object o) throws Exception {
                user = String.valueOf(o);
                setConnection();
                System.out.println(path + " is changed, new user is " + user);
            }

            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path + " is removed");
            }
        });
    }

    private void setConnection(){
        ds.setJdbcUrl(jdbcUrl);
        ds.setUser(user);
        ds.setPassword(passwd);
        ds.setMaxPoolSize(40);
        ds.setMinPoolSize(2);
        ds.setInitialPoolSize(10);
        ds.setMaxStatements(180);
    }

    public Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}
